package cn.tedu.blog.server.controller.system;


import cn.tedu.blog.server.pojo.dto.UserAddNewDTO;
import cn.tedu.blog.server.pojo.dto.UserLoginDTO;
import cn.tedu.blog.server.pojo.vo.UserListVO;
import cn.tedu.blog.server.service.IUserService;
import cn.tedu.blog.server.utils.JsonPage;
import cn.tedu.blog.server.utils.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.security.Principal;
import java.util.List;


/**
 * @author 雷茂林
 * @description: 后台系统用户管理控制器
 * @date
 */
@Api(tags = "1. 系统角色管理")
@Slf4j
@RestController
@RequestMapping("/system/users")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private WebSocketToUser webSocketToUser;

    @ApiOperation("创建用户")
    @ApiOperationSupport(order = 100)
    @PostMapping("/createUser")
    public JsonResult createUser(@RequestBody UserAddNewDTO userAddNewDTO){
        log.debug("接收到客户端提交的请求，参数：{}",userAddNewDTO);
        userService.createUser(userAddNewDTO);
        return JsonResult.ok();
    }



    @ApiOperation("删除用户")
    @ApiOperationSupport(order = 200)
    @PostMapping("/deleteById")
    @PreAuthorize("hasAuthority('/system/users/deleteById')")
    public JsonResult deleteById(@RequestBody UserListVO userListVO){
        log.debug("接收到客户端提交的请求，参数：{}",userListVO.getId());
        userService.deleteById(userListVO.getId());
        return JsonResult.ok();
    }



    @ApiOperation("批量删除用户")
    @ApiOperationSupport(order = 210)
    @PostMapping("/deleteByIds")
    @PreAuthorize("hasAuthority('/system/users/deleteByIds')")
    public JsonResult deleteByIds(@RequestBody List<Long> list){
        log.debug("接收到客户端提交的请求，参数：{}",list);
        userService.deleteByIds(list);
        return JsonResult.ok();
    }



    /**
     * 分配角色
     */
    @ApiOperation("分配角色")
    @ApiOperationSupport(order = 303)
    @PostMapping("/updateRoleByUserId/{userId}")
    public JsonResult updateRoleByUserId(
            @RequestBody Long[] roleArray,@PathVariable("userId") Long userId){
        log.debug("【updateRoleByUserId】接收到客户端提交的请求，参数：{},{}",userId, roleArray);
        userService.updateRoleByUserId(userId,roleArray);
        return JsonResult.ok();
    }


    @ApiOperation("修改用户")
    @ApiOperationSupport(order = 300)
    @PostMapping("/updateById")
    @PreAuthorize("hasAuthority('/system/users/updateById')")
    public JsonResult updateById(@RequestBody UserAddNewDTO userAddNewDTO){
        log.debug("【updateById】接收到客户端提交的请求，参数：{}",userAddNewDTO);
        userService.updateById(userAddNewDTO);
        return JsonResult.ok();
    }


    @ApiOperation("用户修改密码")
    @ApiOperationSupport(order = 301)
    @PostMapping("/updatePasswordByUserName")
    public JsonResult updatePasswordByUserName(@RequestBody UserLoginDTO userLoginDTO){
        log.debug("【updatePasswordByUserName】接收到客户端提交的请求，参数：{}",userLoginDTO);
        userService.updatePasswordByUserName(userLoginDTO);
        return JsonResult.ok();
    }


    @ApiOperation("条件分页查询")
    @ApiOperationSupport(order = 400)
    @PostMapping("/listUsersByCondition")
    public JsonPage<UserListVO> listUsersByCondition(@RequestBody UserListVO userListVO){
        log.debug("【list】接收到客户端提交的请求，参数：{}",userListVO);
        return userService.listByKeyword(userListVO);
    }



    @ApiOperation("获取条件查询的结果集数量")
    @ApiOperationSupport(order = 500)
    @PostMapping("/getCountAll")
    public int getCountAll(@RequestBody UserListVO userListVO){
        log.debug("【countAll】接收到客户端提交的请求，参数：{}",userListVO);
        return userService.getCountAll(userListVO);
    }



    @ApiOperation("根据id获取用户信息")
    @ApiOperationSupport(order = 501)
    @GetMapping("/getBackFillById")
    public UserListVO getBackFillById(Long id){
        log.debug("接收到客户端提交的请求，参数：{}",id);
        return userService.getBackFillById(id);
    }



    @ApiOperation("根据手机号码返回用户账号名称")
    @ApiOperationSupport(order = 502)
    @GetMapping("/getUserNameByPhone")
    public String getUserNameByPhone(String phone){
        log.debug("接收到客户端提交的请求，参数：{}",phone);
        return userService.getUserNameByPhone(phone);
    }



    @ApiOperation("密码登录")
    @ApiOperationSupport(order = 503)
    @PostMapping("/login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO){
        log.debug("接收到客户端提交的请求，参数：{}",userLoginDTO);
        return JsonResult.ok(userService.login(userLoginDTO));
    }



    @ApiOperation("短信登录")
    @ApiOperationSupport(order = 504)
    @GetMapping("/phoneLogin")
    public JsonResult phoneLogin(String phone){
        return JsonResult.ok(userService.phoneLogin(phone));
    }



    @GetMapping("/loginWebSocket")
    public void loginWebSocket(Principal principal){
        String temp = principal.getName().split("=")[2];
        String username = temp.substring(0,temp.length()-1);

        String temp1 = principal.getName().split("=")[1];
        long userId = Long.valueOf(temp1.substring(0,temp1.length()-1).split(",")[0]);

        log.error("即将向{},{}发送通知",userId,username);
        // 推送审核通知(业务暂时不需要)
        try {
            webSocketToUser.sendMessageByUserId(userId,username+"，欢迎回来！");
        } catch (
                IOException e) {
            e.printStackTrace();
        }
    }
}
